package com.github.shiqiyue.rate.limiter.fliter;

import com.github.shiqiyue.rate.limiter.AbstractRateLimiterAction;
import com.github.shiqiyue.rate.limiter.RateLimiterConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * 流量控制filter
 * 
 * @author wwy
 *
 */
public class RateLimiterFilter extends AbstractRateLimiterAction implements Filter {
	
	public RateLimiterFilter() {
	}
	
	public RateLimiterFilter(RateLimiterConfigurer flowControlConfigurer) {
		super(flowControlConfigurer);
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			if (response instanceof HttpServletResponse) {
				if (doRateLimit((HttpServletRequest) request, (HttpServletResponse) response)) {
					chain.doFilter(request, response);
				}
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
		
	}
	
	@Override
	public void destroy() {
	}
	
}
